package rge.orumus.encdb;

import org.simpleframework.xml.Element;
import rge.orumus.androidutils.AndroidUtils;

public abstract class RecordData {
	protected byte[] encryptedData;
	protected EncryptionState encryptionStatus;
	
	@Element
	public String notes;
	
	public enum EncryptionState{
		ES_NOT_SET,
		ES_UNKNOWN,
		ES_ENCRYPTED,
		ES_DECRYPTED
	}
	
	public RecordData(){
		encryptedData = null;
		encryptionStatus = EncryptionState.ES_NOT_SET;
	}
	
	public RecordData(byte[] encryptedData){
		this.encryptedData = encryptedData;
		encryptionStatus = EncryptionState.ES_ENCRYPTED;
	}
	
	public boolean SetEncryptionStatus(EncryptionState newStatus){
		
		switch(newStatus){
		case ES_NOT_SET:
		case ES_UNKNOWN:
			throw new IllegalArgumentException(String.format("SetEncryptionStatus('%1$s')", newStatus));
		case ES_ENCRYPTED:
			{
				if(EncryptionState.ES_ENCRYPTED == encryptionStatus){
					return true;
				}
				String xmlString = AndroidUtils.ObjectToXmlString(this);
				byte[] inBytes = xmlString.getBytes(AndroidUtils.UTF8CHARSET); 
				encryptedData = EncDB.Encrypt(inBytes);
				if(null != encryptedData){
					ClearFields();
					encryptionStatus = EncryptionState.ES_ENCRYPTED;
				}
				break;
			}
		case ES_DECRYPTED:
			{
				if(EncryptionState.ES_DECRYPTED == encryptionStatus){
					return true;
				}
				byte[] outBytes = EncDB.Decrypt(encryptedData);
				if(null != outBytes){
					String xmlString = new String(outBytes, AndroidUtils.UTF8CHARSET);
					SetFieldsFromXml(xmlString);
					encryptionStatus = EncryptionState.ES_DECRYPTED;
				}
				break;
			}
		}
		
		return encryptionStatus == newStatus;
	}
	
	protected void SetFieldsFrom(RecordData rD){
		notes = rD.notes;
	}
	
	public abstract void SetFieldsFromXml(String xmlString);
	
	public void ClearFields(){
		notes = "";
	}
}
